package com.appspot.bibtable.util;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

public final class HtmlUtility
{
	private HtmlUtility()
	{
		// Cannot be instanciated.
	}

	public static String encode(CharSequence rawString)
	{
		if (rawString == null)
		{
			return null;
		}

		StringWriter writer = new StringWriter();
		String result = null;
		try
		{
			encode(rawString, writer);
			result = writer.toString();
			writer.close();
		}
		catch (IOException ex)
		{
		}
		return result;
	}

	public static void encode(CharSequence rawString, Writer output) throws IOException
	{
		if (rawString == null)
		{
			return;
		}

		int length = rawString.length();
		for (int index = 0; index < length; index++)
		{
			char c = rawString.charAt(index);
			switch (c)
			{
				case '&':
					output.write("&amp;");
					break;
				case '<':
					output.write("&lt;");
					break;
				case '>':
					output.write("&gt;");
					break;
				case '"':
					output.write("&quot;");
					break;
				default:
					output.write(c);
					break;
			}
		}
	}
}
